package com.sishu.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sishu.pojo.websocketstudent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class MyWebSocketServer {

    // 维护一个会话集合
    private static Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    // 维护一个teamMap来存储团队资金信息
    private static Map<String, websocketstudent> teamMap = Collections.synchronizedMap(new HashMap<>());

    @OnOpen
    public void onOpen(WebSocketSession session) {
        String sessionId = session.getId();
        System.out.println("新链接: " + sessionId);
        sessions.add(session);
        // 连接成功后立即发送欢迎消息
        try {
            session.sendMessage(new TextMessage("Welcome to the WebSocket server!"));
            System.out.println("Sent welcome message to " + sessionId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(TextMessage message, WebSocketSession session) {

        //获取json数组
        JSONArray jsonArray = JSONArray.parseArray(message.getPayload());
        //定义接受的user数组
        List<websocketstudent> users = new ArrayList<>();
        String s = "";

        //循环json数组，把json数组中的元素转换成User对象
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String sId = jsonObject.getString("sId");
            String groupId = jsonObject.getString("groupId");
            String team = jsonObject.getString("team");
            String sName = jsonObject.getString("sName");
            String levelName = jsonObject.getString("levelName");
            String totalAssets = jsonObject.getString("totalAssets");
            String fluidAssets = jsonObject.getString("fluidAssets");
            String fixedAssets = jsonObject.getString("fixedAssets");
            websocketstudent user = new websocketstudent
                    (sId, team, groupId, levelName, sName, "student", totalAssets, fixedAssets, fluidAssets);

            users.add(user);  //列表中添加对象
        }

        // 更新teamMap中的资金信息 wozhenhaokan?
        for (websocketstudent user : users) {//循环遍历websocketstudenet对象
            if (user.getTeam() != null && !user.getTeam().isEmpty()) {
                if (teamMap.containsKey(user.getTeam())) {
                    websocketstudent teamUser = teamMap.get(user.getTeam());
                    // 更新团队的总资金、流动资金和固定资金
                    teamUser.setTotalAssets(String.valueOf(Integer.parseInt(teamUser.getTotalAssets()) + Integer.parseInt(user.getTotalAssets())));
                    teamUser.setFluidAssets(String.valueOf(Integer.parseInt(teamUser.getFluidAssets()) + Integer.parseInt(user.getFluidAssets())));
                    teamUser.setFixedAssets(String.valueOf(Integer.parseInt(teamUser.getFixedAssets()) + Integer.parseInt(user.getFixedAssets())));
                } else {
                    // 如果teamMap中不存在该team，则创建一个新的对象
                    websocketstudent teamUser = new websocketstudent(user.getTeam(), user.getTeam(), user.getGroupId(), user.getLevelName(), user.getTeam(), "team", user.getTotalAssets(), user.getFixedAssets(), user.getFluidAssets());
                    teamMap.put(user.getTeam(), teamUser);
                }
            }
        }

        //控制台打印插入数据库的结果
        System.out.println(s);

        //将对象集合转成json数组
        String jsonString = JSON.toJSONString(users);

        //把jason数组发送消息给所有客户端
        sendMessageToAll(new TextMessage(jsonString));

    }

    @OnClose
    public void onClose(WebSocketSession session) {
        String sessionId = session.getId();
        System.out.println("Connection closed: " + sessionId);
        sessions.remove(session);
    }

    @OnError
    public void onError(WebSocketSession session, Throwable throwable) {

        String sessionId = session.getId();
        System.out.println("Error in session " + sessionId + ": " + throwable.getMessage());
        sessions.remove(session);
    }

    // 发送消息给所有客户端
    public static void sendMessageToAll(TextMessage message) {
        synchronized (sessions) {

            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    try {

                        session.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void sendMessageTosingle(TextMessage message, String sessionId) {
        for (WebSocketSession session : sessions) {
            if (session.getId().equals(sessionId)) {
                if (session.isOpen()) {
                    try {
                        session.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
